package org.example.springoauth2.securitycommon.util;

import lombok.experimental.UtilityClass;
import org.example.springoauth2.securitycommon.entity.SysUser;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author hzq
 * @date 2021/9/10 16:31
 */
@UtilityClass
public class SecurityUtils {

    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public SysUser getSysUser() {
        SysUser sysUser = getNotRequiredSysUser();
        if (sysUser == null) {
            throw new AuthenticationCredentialsNotFoundException("需要");
        }
        return sysUser;
    }

    public SysUser getNotRequiredSysUser() {
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            // 这里要自己实现 UserAuthenticationConverter  TokenEnhancer
            // 不然获取的到的认证是String类型的用户名 即在本系统的JdbcUser.unionId
            if (principal instanceof SysUser)
                return (SysUser) principal;
        }
        return null;
    }

    public boolean isAuthenticated() {
        return getNotRequiredSysUser() != null;
    }
}
